#ifndef __H_WAVEWRITER__
#define __H_WAVEWRITER__

#include "tstring.h"
#include "file.h"

namespace bl{

	struct RIFF_HEADER
	{
		char	szRiffID[4];		// 'R','I','F','F'
		DWORD	dwRiffSize;
		char	szRiffFormat[4];	// 'W','A','V','E'
	};

	struct WAVE_FORMAT
	{
		WORD	wFormatTag;
		WORD	wChannels;
		DWORD	dwSamplesPerSec;
		DWORD	dwAvgBytesPerSec;
		WORD	wBlockAlign;
		WORD	wBitsPerSample;
	};

	struct FMT_BLOCK
	{
		char		szFmtID[4];	// 'f','m','t',' '
		DWORD		dwFmtSize;
		WAVE_FORMAT	wavFormat;
	};

	struct DATA_BLOCK
	{
		char	szDataID[4];	// 'd','a','t','a'
		DWORD	dwDataSize;
	};

class WaveWriter
{
public:
	WaveWriter()
	{
	}

	void Open(const tchar* file)
	{
		file_.OpenWrite(file);
		RIFF_HEADER header;// = { {'R', 'I', 'F', 'F'}, 0, {'W', 'A', 'V', 'E'}};
		FMT_BLOCK fb;// = { {'f', 'm', 't', ' '},  sizeof(WAVE_FORMAT), {1, 2, 0, 0, 0, 0} };
		DATA_BLOCK db;// = { {'d', 'a', 't', 'a'}, 0};
		file_.Write((uint8*)&header, sizeof(header), NULL);
		file_.Write((uint8*)&fb, sizeof(fb), NULL);
		file_.Write((uint8*)&db, sizeof(db), NULL);
	}

	void Close()
	{
		int fileSize = (int)file_.Size();

		file_.Seek(0, File::SEEK_FROM_START);
		RIFF_HEADER header = { {'R', 'I', 'F', 'F'}, fileSize-8 , {'W', 'A', 'V', 'E'}};
		file_.Write((uint8*)&header, sizeof(header), NULL);
		
		FMT_BLOCK fb = { {'f', 'm', 't', ' '},  sizeof(WAVE_FORMAT)
			, {wavfmt_.wFormatTag, wavfmt_.nChannels, wavfmt_.nSamplesPerSec, wavfmt_.nAvgBytesPerSec, wavfmt_.nBlockAlign, wavfmt_.wBitsPerSample} };
		file_.Write((uint8*)&fb, sizeof(fb), NULL);

		DATA_BLOCK db = { {'d', 'a', 't', 'a'}, fileSize - sizeof(RIFF_HEADER) - sizeof(FMT_BLOCK) - sizeof(DATA_BLOCK)};
		file_.Write((uint8*)&db, sizeof(db), NULL);

		file_.Close();
	}

	void SetFormat(const WAVEFORMATEX* fmt)
	{
		wavfmt_ = *fmt;
	}

	void Write(const unsigned char* buff, unsigned int len)
	{
		file_.Write(buff, len, NULL);
	}

private:
	File file_;

	WAVEFORMATEX wavfmt_;
};



}

#endif